package com.niji.littly_donkey_android.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.*;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.volley.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.makeramen.roundedimageview.RoundedImageView;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.activity.GetPhoneCodeActivity;
import com.niji.littly_donkey_android.activity.IndexActivity;
import com.niji.littly_donkey_android.activity.OrderFillActivity;
import com.niji.littly_donkey_android.bean.Fans;
import com.niji.littly_donkey_android.bean.Ticket;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.util.DateUtils;
import com.niji.littly_donkey_android.util.JsonUtil;
import com.niji.littly_donkey_android.util.NetworkGlideImageLoader;
import com.niji.littly_donkey_android.util.UrlUtil;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TicketAdapter extends ArrayAdapter<Ticket> {


    private static final String TAG = "TicketAdapter";

    private Context context;

    private Activity activity;

    private View view;

    private Integer uu_aid;

    private Integer uu_tid;

    private Integer uu_pid;

    private Integer uu_lid;

    private String ticketName;

    private String attractions_id;



    private int flag = 1;

    public TicketAdapter(Context context, ArrayList<Ticket> members)
    {
        super(context,0, members);
        this.context = context;
        this.activity = (Activity) context;
    }
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        this.view = convertView;
        Ticket ticket = getItem(position);

        if(convertView == null)
        {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_screen_ticket, parent, false);
        }
        TextView screen_ticket_name = convertView.findViewById(R.id.screen_ticket_name);
        TextView screen_ticket_price = convertView.findViewById(R.id.screen_ticket_price);
        TextView screen_ticket_saled = convertView.findViewById(R.id.screen_ticket_saled);
        TextView screen_ticket_id = convertView.findViewById(R.id.screen_ticket_id);
        Button screen_ticket_order = convertView.findViewById(R.id.screen_ticket_order);
        Map<String, Object> hour_prices = ticket.getHour_price();
        ArrayList<Map<String, Object>> date_prices = ticket.getDate_price();
        String date = null;
        attractions_id = String.valueOf(ticket.getAttractions_id());
        if(hour_prices != null){
            if(hour_prices.size() != 0){
                String retail_price = (String) hour_prices.get("buy_price");
                screen_ticket_price.setText("￥" + retail_price);
                date = (String) hour_prices.get("date");
            }
        }else {
            if(date_prices != null){
                if(date_prices.size() != 0){
                    String retail_price = (String) date_prices.get(0).get("buy_price");
                    screen_ticket_price.setText("￥" + retail_price);
                    date = (String) date_prices.get(0).get("date");
                }

            }
        }
        screen_ticket_id.setText("" + ticket.getUUid());
        screen_ticket_name.setText(ticket.getUUtitle());
        String finalDate = date;
        screen_ticket_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(context, OrderFillActivity.class);
//                intent.putExtra("attractions_id",String.valueOf(ticket.getAttractions_id()));
//                intent.putExtra("playtime", finalDate);
//                activity.startActivity(intent);
                uu_aid = Integer.parseInt(ticket.getUUaid());
                uu_tid = Integer.parseInt(ticket.getUUid());
                uu_pid = Integer.parseInt(ticket.getUUpid());
                uu_lid = Integer.parseInt(ticket.getUUlid());
                ticketName = ticket.getUUtitle();

                showPopupWindow(v);

            }
        });




        return convertView;
    }

    /**
     * 显示
     *
     * @param targetView 需要显示的内容view
     * @return
     */
    public void showPopupWindow(View targetView) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(context).inflate(
                R.layout.activity_mix, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,  ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
        backgroundAlpha(0.5f);
        Button cancel_comment = contentView.findViewById(R.id.cancel_order);
        RelativeLayout ticket_order1 = contentView.findViewById(R.id.ticket_order1);
        RelativeLayout ticket_order2 = contentView.findViewById(R.id.ticket_order2);
        RelativeLayout ticket_order3 = contentView.findViewById(R.id.ticket_order3);
        ImageView ticket_order_checked1 = contentView.findViewById(R.id.ticket_order_checked1);
        ImageView ticket_order_checked2 = contentView.findViewById(R.id.ticket_order_checked2);
        ImageView ticket_order_checked3 = contentView.findViewById(R.id.ticket_order_checked3);
        TextView ticket_order_money = contentView.findViewById(R.id.ticket_order_money);
        TextView ticket_order_money1 = contentView.findViewById(R.id.ticket_order_money1);
        TextView ticket_order_money2 = contentView.findViewById(R.id.ticket_order_money2);
        TextView ticket_order_money3 = contentView.findViewById(R.id.ticket_order_money3);
        TextView ticket_order_playtime1 = contentView.findViewById(R.id.ticket_order_playtime1);
        TextView ticket_order_playtime2 = contentView.findViewById(R.id.ticket_order_playtime2);
        TextView ticket_order_playtime3 = contentView.findViewById(R.id.ticket_order_playtime3);
        TextView ticket_order_time1 = contentView.findViewById(R.id.ticket_order_time1);
        TextView ticket_order_time2 = contentView.findViewById(R.id.ticket_order_time2);
        TextView ticket_order_time3 = contentView.findViewById(R.id.ticket_order_time3);
        TextView ticket_order_name = contentView.findViewById(R.id.ticket_order_name);
        CalendarView calendarView = contentView.findViewById(R.id.calendarView);
        Button order_ticket = contentView.findViewById(R.id.order_ticket);
        ticket_order_name.setText(ticketName);
        getTicketPriceByTime(new Date().getTime(),ticket_order_money);
        getTicketTimeByTime(new Date().getTime(),ticket_order_money1,ticket_order_playtime1);
        getTicketTimeByTime(new Date().getTime() + 86400000 ,ticket_order_money2,ticket_order_playtime2);
        getTicketTimeByTime(new Date().getTime() + 172800000,ticket_order_money3,ticket_order_playtime3);
        ticket_order_time1.setText(DateUtils.getTicketDate(new Date().getTime()));
        ticket_order_time2.setText(DateUtils.getTicketDate(new Date().getTime() + 86400000));
        ticket_order_time3.setText(DateUtils.getTicketDate(new Date().getTime() + 172800000));
        ticket_order1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ticket_order1.setBackground(contentView.getResources().getDrawable(R.drawable.ticket_checked));
                ticket_order2.setBackground(contentView.getResources().getDrawable(R.drawable.ticket_not_checked));
                ticket_order3.setBackground(contentView.getResources().getDrawable(R.drawable.ticket_not_checked));
                ticket_order_checked1.setVisibility(View.VISIBLE);
                ticket_order_checked2.setVisibility(View.INVISIBLE);
                ticket_order_checked3.setVisibility(View.INVISIBLE);
                flag = 1;
            }
        });
        ticket_order2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ticket_order2.setBackground(contentView.getResources().getDrawable(R.drawable.ticket_checked));
                ticket_order1.setBackground(contentView.getResources().getDrawable(R.drawable.ticket_not_checked));
                ticket_order3.setBackground(contentView.getResources().getDrawable(R.drawable.ticket_not_checked));
                ticket_order_checked2.setVisibility(View.VISIBLE);
                ticket_order_checked1.setVisibility(View.INVISIBLE);
                ticket_order_checked3.setVisibility(View.INVISIBLE);
                flag = 2;
            }
        });
        ticket_order3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ticket_order3.setBackground(contentView.getResources().getDrawable(R.drawable.ticket_checked));
                ticket_order2.setBackground(contentView.getResources().getDrawable(R.drawable.ticket_not_checked));
                ticket_order1.setBackground(contentView.getResources().getDrawable(R.drawable.ticket_not_checked));
                ticket_order_checked3.setVisibility(View.VISIBLE);
                ticket_order_checked2.setVisibility(View.INVISIBLE);
                ticket_order_checked1.setVisibility(View.INVISIBLE);
                flag = 3;
            }
        });

        calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {

            }

            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                boolean b = checkDate(calendar.getYear(), calendar.getMonth(), calendar.getDay());
                if(!b){
                    TextView tv_month_day = contentView.findViewById(R.id.tv_month_day);
                    TextView tv_year = contentView.findViewById(R.id.tv_year);
                    TextView tv_lunar = contentView.findViewById(R.id.tv_lunar);
                    tv_month_day.setText("" + calendar.getDay());
                    tv_year.setText("" + calendar.getYear());
                    tv_lunar.setText(calendar.getMonth() + "月");
                    getTicketPriceByTime(calendar.getTimeInMillis(),ticket_order_money);
                    getTicketTimeByTime(calendar.getTimeInMillis(),ticket_order_money1,ticket_order_playtime1);
                    getTicketTimeByTime(calendar.getTimeInMillis() + 86400000 ,ticket_order_money2,ticket_order_playtime2);
                    getTicketTimeByTime(calendar.getTimeInMillis() + 172800000,ticket_order_money3,ticket_order_playtime3);
                    ticket_order_time1.setText(DateUtils.getTicketDate(calendar.getTimeInMillis()));
                    ticket_order_time2.setText(DateUtils.getTicketDate(calendar.getTimeInMillis() + 86400000));
                    ticket_order_time3.setText(DateUtils.getTicketDate(calendar.getTimeInMillis() + 172800000));
                }else {
                    Toast.makeText(context,"请选择今日之后的日期",Toast.LENGTH_SHORT).show();
                }

            }
        });

        cancel_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                backgroundAlpha(1f);
            }
        });
        order_ticket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, OrderFillActivity.class);
                intent.putExtra("attractions_id", attractions_id);
                String time = DateUtils.getTicketDate(new Date().getTime());
                String ticketPrice = null;
                String ticketName = ticket_order_name.getText().toString().trim();
                if(flag == 1){
                    time = ticket_order_playtime1.getText().toString().trim();
                    ticketPrice = ticket_order_money1.getText().toString().trim().split("￥")[1];
                }else if(flag == 2){
                    time = ticket_order_playtime2.getText().toString().trim();
                    ticketPrice = ticket_order_money2.getText().toString().trim().split("￥")[1];
                }else if(flag == 3){
                    time = ticket_order_playtime3.getText().toString().trim();
                    ticketPrice = ticket_order_money3.getText().toString().trim().split("￥")[1];
                }
                intent.putExtra("ticketPrice", ticketPrice);
                intent.putExtra("ticketName", ticketName);
                intent.putExtra("uu_aid", String.valueOf(uu_aid));
                intent.putExtra("uu_lid",  String.valueOf(uu_lid));
                intent.putExtra("uu_tid",  String.valueOf(uu_tid));
                intent.putExtra("playtime", time);
                activity.startActivity(intent);
            }
        });

//        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//
////                Log.i("mengdd", "onTouch : ");
//
//                return false;
//                // 这里如果返回true的话，touch事件将被拦截
//                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
//            }
//        });
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(context.getResources().getDrawable(
                R.drawable.shape_top));
        // 设置好参数之后再show
        int[] location = new int[2];
        targetView.getLocationOnScreen(location);
        popupWindow.showAtLocation(targetView, Gravity.LEFT|Gravity.BOTTOM,0,-location[1]);


    }

    private boolean checkDate(int year, int month, int day) {
        String ticketDate = DateUtils.getTicketDate(new Date().getTime());
        String[] data = ticketDate.split("-");
        if (Integer.parseInt(data[0]) > year){
            return true;
        }else if (Integer.parseInt(data[0]) == year){
           if(Integer.parseInt(data[1]) > month){
               return true;
           }else if(Integer.parseInt(data[1]) == month){
               if(Integer.parseInt(data[2]) > day){
                   return true;
               }else {
                   return false;
               }
           }else {
               return false;
           }
        }else {
            return false;
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha)
    {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        activity.getWindow().setAttributes(lp); activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    private void getTicketPriceByTime(long time,TextView textView){
        String ticketDate = DateUtils.getTicketDate(time);
        String url = UrlUtil.URL + "/attractions/ticket/price?start_date=" + ticketDate + "&uu_aid=" + uu_aid + "&uu_tid=" + uu_tid + "&uu_pid=" + uu_pid;
        RequestQueue requestQueue= Volley.newRequestQueue(context);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        Map<String,Object> data = (Map<String, Object>) map.get("data");
                        Map<String,Object> hour_price = (Map<String, Object>) data.get("hour_price");
                        ArrayList<Map<String,Object>> date_price = (ArrayList<Map<String, Object>>) data.get("date_price");
                        if(hour_price !=null){
                            String buy_price = (String) hour_price.get("buy_price");
                            textView.setText("￥" + buy_price);
                        }else {
                            if(date_price != null){
                                if(date_price.size() > 0){
                                    String buy_price = (String) date_price.get(0).get("buy_price");
                                    textView.setText("￥" + buy_price);
                                }
                            }
                        }
                    } else if(code == -1){
                        Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(context, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode","-1");
                        activity.startActivity(intent);
                        activity.finish();
                    }else {
                        Object message = map.get("message");
                        Toast.makeText(context, message.toString(), Toast.LENGTH_SHORT).show();
                        activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        activity.finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.getMessage(), volleyError);
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(context).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };

        requestQueue.add(stringRequest);
    }

    private void getTicketTimeByTime(long time,TextView textView,TextView textView1){
        String ticketDate = DateUtils.getTicketDate(time);
        String url = UrlUtil.URL + "/attractions/ticket/price?start_date=" + ticketDate + "&uu_aid=" + uu_aid + "&uu_tid=" + uu_tid + "&uu_pid=" + uu_pid;
        RequestQueue requestQueue= Volley.newRequestQueue(context);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        Map<String,Object> data = (Map<String, Object>) map.get("data");
                        Map<String,Object> hour_price = (Map<String, Object>) data.get("hour_price");
                        ArrayList<Map<String,Object>> date_price = (ArrayList<Map<String, Object>>) data.get("date_price");
                        if(hour_price !=null){
                            String buy_price = (String) hour_price.get("buy_price");
                            textView.setText("￥" + buy_price);
                            ArrayList<Map<String,String>> periodList = (ArrayList<Map<String, String>>) hour_price.get("periodList");
                            Map<String, String> map1 = periodList.get(periodList.size() - 1);
                            String start_time = map1.get("start_time");
                            textView1.setText(ticketDate + " " + start_time);
                        }else {
                            if(date_price != null){
                                if(date_price.size() > 0){
                                    String buy_price = (String) date_price.get(0).get("buy_price");
                                    textView.setText("￥" + buy_price);
                                    textView1.setText(ticketDate);
                                }
                            }
                        }
                    } else if(code == -1){
                        Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(context, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode","-1");
                        activity.startActivity(intent);
                        activity.finish();
                    }else {
                        Object message = map.get("message");
                        Toast.makeText(context, message.toString(), Toast.LENGTH_SHORT).show();
                        activity.overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        activity.finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.getMessage(), volleyError);
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(context).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };

        requestQueue.add(stringRequest);
    }



}



